package cn.com.callback

import cn.com.kh.KHUtil
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
/**
 *
 * @Title: aipHSTActivity
 * @Description:华盛证券 将活动详情导入更新上customer_guid、objective_guid --内部接口
 * @author: chieh
 * @date 2021-12-27 10:28:00
 *
 */

public class aipHSTActivity implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTActivity.class);
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();

        log.debug("getMethod:" + getMethod);
        long endTime ;
        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            long startTime = System.currentTimeMillis();

            // 调用处理信息
            JSONObject inObject = JSONObject.parseObject(inData);
            log.debug("处理前的Json：" + inObject.toString());
            def batchid = inObject.getString("batchid");//批次id
            
            log.debug("解析信息-" + "batchid: " + batchid);
            if (batchid!=''&&batchid!=null) {
                outData = allocationData(eliteBean,batchid,dataSourceID);
            }else{
				log.error("处理失败(批次号为空错误)!");
                endTime = System.currentTimeMillis();
                return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(批次号为空错误),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
			}

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        log.debug("活动更新完成返回结果:" + outData);

        return outData;
    }

    // 处理开发名单任务
    public static String allocationData(EliteBean eliteBean,String batchid,String dataSourceID) {

        long startTime = System.currentTimeMillis();
        long endTime = System.currentTimeMillis();

        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createdate = dateformat.format(System.currentTimeMillis());

        // 定义返回对象
        JSONObject resultJson = new JSONObject();

       try {
		   /*
			//1.更新hst_activity_batch_list 表customer_guid
			def selectcustomerguidSQL = "select  customer.customer_guid as customerguid,customer.CUSTOMER_ID as customerid from hst_activity_batch_list,customer where hst_activity_batch_list.hst_no=customer.CUSTOMER_ID and batchid = '" + batchid + "' and hst_activity_batch_list.result_code !='-3'";
			log.debug("查询分配数量selectcustomerguidSQL="+selectcustomerguidSQL);

			List selectcustomerguidList = eliteBean.chaxun_sql(selectcustomerguidSQL, "dataSource");
			def customerguidListNum = selectcustomerguidList.size();
			log.debug("待分配customerguid ListNum=" + customerguidListNum);
            
			int m=0;
			int n=0;
			int arrInt=100;
			//轮询分配次数
			double number=customerguidListNum*1.0/arrInt;
			log.debug("轮询分配次数number :" + number);
			//轮询次数向上取整
			int count=Math.ceil(number);
			log.debug("轮询次数取整count :" + count);
			int yscount=customerguidListNum%arrInt;
			log.debug("yscount :" + yscount);
			
			String[] customerguidSQL = new String[arrInt];
            for (int i = 0; i < customerguidListNum; i++) {
				Map selectcustomerguidSQLMap = selectcustomerguidList.get(i);

				def customerguid = selectcustomerguidSQLMap.get("customerguid");
				def customerid = selectcustomerguidSQLMap.get("customerid");
				customerguidSQL[m]="update hst_activity_batch_list set customer_guid='" + customerguid + "' where hst_no='" + customerid + "' and batchid = '" + batchid + "' and  result_code !='-3'";	
				m++;
				if(m==arrInt||(n==count-1&&m==yscount)){
					//将数据插入数据库
					log.debug("customerguidSQL："+customerguidSQL.toString());
					int[] customerguidsqlResult = eliteBean.updateBatch(customerguidSQL, dataSourceID);
					log.debug("提交数据库操作SQL结果:" + customerguidsqlResult.toString());
					customerguidSQL = new String[arrInt];
					m=0;
					n++;
				}
				
			}
			
			
			//2.更新hst_activity_batch_list 表objective_guid
			def selecobjectiveguidSQL = "select  objective.objective_guid as objectiveguid,objective.CUSTOMER_GUID as customerguid from hst_activity_batch_list,objective where hst_activity_batch_list.customer_guid = objective.CUSTOMER_GUID and batchid = '" + batchid + "' and hst_activity_batch_list.result_code !='-3' and objective.map_id='MY48ZX'";
			log.debug("查询分配数量selecobjectiveguidSQL="+selecobjectiveguidSQL);

			List selectobjectiveguidList = eliteBean.chaxun_sql(selecobjectiveguidSQL, "dataSource");
			def objectiveguidListNum = selectobjectiveguidList.size();
			log.debug("待分配objectiveguid ListNum=" + objectiveguidListNum);
            
			m=0;
			n=0;
			//轮询分配次数
			double number1=objectiveguidListNum*1.0/arrInt;
			log.debug("轮询分配次数number1 :" + number1);
			//轮询次数向上取整
			int count1=Math.ceil(number1);
			log.debug("轮询次数取整count1 :" + count1);
			int yscount1=objectiveguidListNum%arrInt;
			log.debug("yscount1 :" + yscount1);
			String[] objectiveguidSQL = new String[arrInt];
            for (int j = 0; j < objectiveguidListNum; j++) {
				Map selectobjectiveguidSQLMap = selectobjectiveguidList.get(j);

				def objectiveguid = selectobjectiveguidSQLMap.get("objectiveguid");
				def customerguid = selectobjectiveguidSQLMap.get("customerguid");
				
				objectiveguidSQL[m]="update hst_activity_batch_list set objective_guid='" + objectiveguid + "' where customer_guid='" + customerguid + "' and batchid = '" + batchid + "' and  result_code !='-3'";	
				m++;
				if(m==arrInt||(n==count1-1&&m==yscount1)){
					//将数据插入数据库
					log.debug("objectiveguidSQL："+objectiveguidSQL.toString());
					int[] objectiveguidsqlResult = eliteBean.updateBatch(objectiveguidSQL, dataSourceID);
					log.debug("提交数据库操作SQL结果:" + objectiveguidsqlResult.toString());
					objectiveguidSQL = new String[arrInt];
					m=0;
					n++;
				}				
			}
			*/
			def customer_guidresult = eliteBean.update("update hst_activity_batch_list,customer set hst_activity_batch_list.customer_guid=customer.customer_guid where hst_activity_batch_list.hst_no=customer.CUSTOMER_ID and batchid = '" + batchid + "'", "dataSource");
			log.debug("提交数据库操作customer_guidresult结果:" + customer_guidresult);

			def objective_guidresult = eliteBean.update("update hst_activity_batch_list,objective set hst_activity_batch_list.objective_guid=objective.objective_guid where hst_activity_batch_list.customer_guid = objective.CUSTOMER_GUID  and batchid ='" + batchid + "' and objective.map_id='MY48ZX'", "dataSource");
			log.debug("提交数据库操作objective_guidresult结果:" + objective_guidresult);

			
            // 生成处理完成时间
            endTime = System.currentTimeMillis();
			
            // 包装拼接返回JSONObject
            resultJson.put("resultcode", 1);
            resultJson.put("resultmessage", "处理完成,调用问题处理时长(毫秒):" + (endTime - startTime));
        } catch (Exception e) {
            endTime = System.currentTimeMillis();
            resultJson.put("resultcode", 4);
            resultJson.put("resultmessage", "处理失败:(" + e.getMessage() + ")" + "处理完成,调用问题处理时长(毫秒):" +(endTime -startTime));

        }

        return resultJson.toString();
    }
	
	// 解析Json值
		public static String GetJV(JSONObject inJson, String getKey) {
			String Rev_Value = null;
			try {
				Rev_Value = inJson.getString(getKey);
			} catch (Exception e) {
				try {
					Rev_Value = String.valueOf(inJson.getInt(getKey));
				} catch (Exception e1) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
					} catch (Exception e2) {
						try {
							Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
						} catch (Exception e3) {
							Rev_Value = "";
						}
					}
				}
			} finally {
				if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
					Rev_Value = "";
				} else {
				}
			}
			log.debug("解析-k=" + getKey + " v=" + Rev_Value);
			return Rev_Value;
		}

}
